import { createRouter, createWebHashHistory } from 'vue-router';
import { useCookies } from 'vue3-cookies';
import { showFailToast } from 'vant';
import { POST } from '@/utils/request';

const routes = [];

const modules = import.meta.globEager('./routes/*.js');

Object.values(modules).forEach((item) => {
	if (item.default) routes.push(item.default);
});

// console.log(routes);

const router = createRouter({
	history: createWebHashHistory(),
	routes,
});

const vueCookies = useCookies().cookies

router.beforeEach(async (to, from, next) => {
	if (to.meta?.auth) {
		const cookie = vueCookies.get('business');

		if (!cookie || Object.getOwnPropertyNames(cookie).length <= 0) {
			showFailToast({
				message: '请先登录',
				duration: 1000,
			});

			router.push('/business/login');
			return;
		}

		const id = cookie.hasOwnProperty('id') ? cookie.id : null;
		const mobile = cookie.hasOwnProperty('mobile') ? cookie.mobile : null;

		if (!id || !mobile) {
			showFailToast({
				message: '非法登录',
				duration: 1000,
			});
			router.push('/business/login');
			return;
		}

		const result = await POST({
			url: '/business/check',
			params: { id, mobile },
		});

		if (result.code === 0) { 
			// 请求失败移除cookie
			vueCookies.remove('business')

			showFailToast({
				message: '非法登录',
				duration: 1000,
			});
			router.push('/business/login');
			return;
		}
		// 验证成功
		vueCookies.set('business', result.data)
		next();

	} else {
		next();
	}
});

export default router;
